package com.bailan.foreat.service.impl;

import com.bailan.foreat.entity.Address;
import com.bailan.foreat.mapper.AddressMapper;
import com.bailan.foreat.service.AddressService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ste
 * @since 2023-02-21 07:50:43
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Autowired
    AddressMapper addressMapper;

    @Override
    public List<Address> getAll(Integer userId) {

        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        List<Address> addressList = addressMapper.selectList(queryWrapper);

        return addressList;
    }

    @Override
    @Transactional
    public void addAddress(Integer userId, Address address) {

        if (address.getIsDefault() == 1) {
            //将原有的所有地址置为非默认地址
            addressMapper.clearIsDefault(userId);
        }

        //再写入新的地址
        address.setUserId(userId);
        address.setStatus(0);

        addressMapper.insert(address);

    }

    @Override
    public Address selectById(Integer addressId) {
        Address address = addressMapper.selectById(addressId);
        return address;
    }

    @Override
    @Transactional
    public void updateAddress(Address address) {
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", address.getUserId());
        wrapper.eq("is_default", 1);
        List<Address> list = addressMapper.selectList(wrapper);

        //判断有无默认地址,如果有才能改默认字段
        if (address.getIsDefault() == 1 && list != null) {
            //将原有的所有地址置为非默认地址
            addressMapper.clearIsDefault(address.getUserId());
        }

        //判断有无默认地址,如果没有则改强制设为默认地址
        if (address.getIsDefault() == 0 && list == null) {
            address.setIsDefault(1);
        }

        //再写入新的地址
        addressMapper.updateById(address);
    }

    @Override
    public void deleteById(Integer addressId) {
        addressMapper.deleteAddressById(addressId);
    }
}
